import OSS from 'ali-oss';
import { ossApkAuth, ossAuth, ossImgProcess } from '@/api/ossAuthData';
import { guid } from '@/utils/common';

export default {
  client: null,

  // 上传apk
  uploadApk: async function (file: File, target: string, type = 'apk') {
    const res = await ossApkAuth({});
    if (res.status !== 200) return;
    const resData = res.data;
    this.client = new OSS({
      region: resData.region,
      accessKeyId: resData.accessKeyId,
      accessKeySecret: resData.accessKeySecret,
      bucket: resData.bucket,
      stsToken: resData.securityToken,
    });
    try {
      const fileName = `enterpriseSys/${target}/${guid() + `.${type}`}`;
      return this.client
        .put(fileName, file, { headers: { 'x-oss-forbid-overwrite': false } })
        .then((result) => {
          return result.url;
        })
        .catch((err) => {
          console.log('apk上传失败', err);
          throw err;
        });
    } catch (e) {
      console.error(e, '失败了');
      throw e;
    }
  },

  // 上传图片
  uploadImage: async function (file: File, target: string, type = 'jpg', suffix = null) {
    const res = await ossAuth({});
    if (res.status !== 200) return;
    const resData = res.data;
    this.client = new OSS({
      region: resData.region,
      accessKeyId: resData.accessKeyId,
      accessKeySecret: resData.accessKeySecret,
      bucket: resData.bucket,
      stsToken: resData.securityToken,
    });

    try {
      const fileName = `/temp/${guid() + `.${type}`}`; // 指定上传到OSS的文件路径和文件名
      return this.client
        .put(fileName, file, { headers: { 'x-oss-forbid-overwrite': false } })
        .then(async (result) => {
          const res = await ossImgProcess({
            url: result.name, //入参原文件路径
            thumb: {
              mode: 0,
              size: {
                width: 0,
                height: 0,
              },
            },
            format: null,
            targetPath: "enterpriseSys/" + target,
          });
          if (suffix) {
            return res.data.fullUrl + suffix;
          } else {
            return res.data.fullUrl;
          }
        })
        .catch((err) => {
          console.log(err, 'err');
          throw err;
        });
    } catch (e) {
      console.error(e, '失败了');
    }
  },
};
